package com.whlilong.jxc.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Hashtable;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.whlilong.jxc.db.ConnectImpl;
import com.whlilong.jxc.db.HibernateSessionFactory;
import com.whlilong.jxc.service.db.IConnection;
import com.whlilong.jxc.sys.NoOpEntityResolver;
import com.whlilong.jxc.util.FileUtil;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "com.whlilong.jxc";

	// The shared instance
	private static Activator plugin;

	private ServiceRegistration dbServiceRegistration;

	/**
	 * The constructor
	 */
	public Activator() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
	 * )
	 */
	@SuppressWarnings("unchecked")
	public void start(BundleContext context) throws Exception {
		dbServiceRegistration = context.registerService(IConnection.class
				.getName(), new ConnectImpl(), new Hashtable());
		super.start(context);
		copyXML();
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
	 * )
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		if (dbServiceRegistration != null)
			dbServiceRegistration.unregister();
		super.stop(context);
		HibernateSessionFactory.close();
	}

	/**
	 * Returns the shared instance
	 * 
	 * @return the shared instance
	 */
	public static Activator getDefault() {
		return plugin;
	}

	private void copyXML() throws IOException, DocumentException {
		File file = new File(FileUtil.getWorkspace(), "hibernate_derby.cfg.xml");
		if (!file.exists()) {
			file.createNewFile();
			copyXML(file);
		} else {
			SAXReader reader = new SAXReader();
			Document doc = reader.read(file);
			Element sessionfactory = (Element) doc.getRootElement().content()
					.get(0);
			List children = sessionfactory.content();
			for (Object obj : children) {
				if (obj instanceof Element) {
					Element dbUrl = (Element) obj;
					dbUrl.setText("jdbc:hsqldb://" + FileUtil.getWorkspace()
							+ "data/jxcdb");
					break;
				}
			}
			printDocument(doc, file);

		}
	}

	@SuppressWarnings("unchecked")
	private void copyXML(File file) throws DocumentException, IOException {
		URL url = this.getBundle().getEntry("hibernate_derby.cfg.xml");
		SAXReader reader = new SAXReader();
		Document doc = reader.read(url);
		Element sessionfactory = (Element) doc.getRootElement().content()
				.get(0);
		List children = sessionfactory.content();
		for (Object obj : children) {
			if (obj instanceof Element) {
				Element dbUrl = (Element) obj;
				dbUrl.setText("jdbc:hsqldb://" + FileUtil.getWorkspace()
						+ "data/jxcdb");
				break;
			}
		}
		printDocument(doc, file);
	}

	public void printDocument(Document doc, File file) throws IOException {
		FileOutputStream output = new FileOutputStream(file);
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		XMLWriter writer = new XMLWriter(new OutputStreamWriter(output), format);
		writer.write(doc);
		writer.close();
	}

}
